<?php

/*
	CONFIRM DELETE js
	-----------------
	<a href="http://domain.com/admin/delete-file.php?file_id=4" onclick="return confirm('Are you sure you want to delete this file?'); return false;">Delete File</a>

  VALIDATION
  -----------
  function validate()
  {
  if (document.[form_name].[control_name].value == "")
  {
  alert("Message");
  document.[form_name].[control_name].focus();
  return false;
  }
  }

  CRUD
  ------
  ---------------------------------------------------------------------------------------------------------
  INSERT
  ------

  try {
  $mysqli = @new mysqli("localhost", "ODBC", "", "mytasks");
  $stmt = $mysqli->prepare("INSERT INTO task_user (usr_username, usr_password) VALUES (?, ?)");
  $stmt->bind_param("ss", $_POST['username'], $_POST['password']);
  $stmt->execute();
  header("Location: login.php");
  exit();
  } catch (Exception $e) {
  echo "<font color='red'>" . $e . "</font>";
  }

  ---------------------------------------------------------------------------------------------------------
  ---------------------------------------------------------------------------------------------------------
  SELECT
  ------

  try {
            $mysqli = @new mysqli("localhost", "ODBC", "", "db_myaccounts");
            if (mysqli_connect_errno()) {
                echo "<font color='red'>Database Error: " . mysql_connect_error() . "</font>";
                exit();
            } else {
                echo "<br />";
                echo "<table border='1'>";
                $stmt = $mysqli->prepare("SELECT task_date, task_description, DATE_FORMAT(task_due_date, '%Y-%m-%d (%W)'), usr_ID FROM tasks  WHERE usr_ID = $id ORDER BY task_due_date");
                if ($stmt) {
                    $stmt->execute();
                    $stmt->bind_result($task_date, $task_description, $task_due_date, $user_ID);
                    while ($stmt->fetch()) {
                        echo "<tr>";
                        
                        echo "</tr>";
                    }
                }
                echo "</table>";
            }
            $mysqli->close();
        } catch (Exception $e) {
            echo "<font color='red'>" . $e . "</font>";
        }

  ---------------------------------------------------------------------------------------------------------
  ---------------------------------------------------------------------------------------------------------
  UPDATE
  ------

 
  try {
  //Connect database
  $mysqli = @new mysqli('localhost', 'ODBC', '', 'free_exam_db');
  $sql = "UPDATE subject SET sub_name = ? WHERE sub_name = ?";
  if ($stmt = $mysqli->prepare($sql)) {
  $stmt->bind_param('ss', $new_subject, $subject);
  $stmt->execute();
  }
  $stmt->close();
  return 1;
  } catch (Exception $error_string) {
  return $error_string;
  }
 

  ---------------------------------------------------------------------------------------------------------
  ---------------------------------------------------------------------------------------------------------
  DELETE
  ------

  try {
  session_start();
  $_SESSION['timeout'] = time();
  $task = base64_decode($_REQUEST['del']);
  $mysqli = @new mysqli("localhost", "ODBC", "", "mytasks");
  $stmt = $mysqli->prepare("DELETE FROM tasks WHERE task_description = ?");
  $stmt->bind_param("s", $task);
  $stmt->execute();
  header("Location: index.php");
  exit();
  } catch (Exception $e) {
  echo "<font color='red'>" . $e . "</font>";
  }

  ---------------------------------------------------------------------------------------------------------
 */

 //
 //Makes plaintext a link
 function make_clickable($text) {
  return preg_replace_callback(
    '#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', 
    create_function(
      '$matches',
      'return "<a href=\'{$matches[0]}\'>{$matches[0]}</a>";'
    ),
    $text
  );
}
 

 
 function changeTextToUrl($text, $url)
 {
	// The Regular Expression filter
	$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

	// The Text you want to filter for urls
	//$text = "The text you want to filter goes here. http://google.com";

	// Check if there is a url in the text
	if(preg_match($reg_exUrl, $text, $url)) {
		// make the urls hyper links
		return preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);
	} else {
		// if no urls in the text just return the text
		return $text;

	}
 }


function add_spaces($num_spaces = 1) {
    for ($count = 1; $count <= $num_spaces; $count++) {
        echo "&nbsp;";
    }
}

//
function calculate_percentage($counter, $maximum, $dec) {
    $percentage = ($counter * 100) / $maximum;
    return round($percentage, $dec, PHP_ROUND_HALF_UP) . '%';
}

//Prints a list of \objects
function print_list(array $listOfObjects) {
    foreach ($listOfObjects as $object) {
        echo (string) $object->getName(), "\n";
    }
}

//






// Create an anchor tag from a passed url
// Can also create a mailto tag, change the anchor text, 
// and apply a css class
function CreateAnchorTag($url, $is_email, $urltext = "", $cssclass = "") {
    $anchortag = "";

// Prepare the css class if requested
    if (strlen($cssclass) > 0) {
        $cssclass = "class=\"" . $cssclass . "\" ";
    }

// Clean URL text
    if (!strlen($urltext) > 0) {
        $urltext = $url;
    }

// If a URL was passed create an anchor tag
    if (strlen($url) > 0) {
        if ($is_email == true) {
            $anchortag = "<a " . $cssclass . "href=\"mailto:" .
                    $url . "\">" . $urltext . "</a>";
        } else {
            $anchortag = "<a " . $cssclass . "href=\"" .
                    $url . "\">" . $urltext . "</a>";
        }
    }

    return $anchortag;
}





//Perform a safe redirect
function force_redirect($url, $delay = 0) {
    if (!headers_sent() && $delay == 0) {
        ob_end_clean();
        header("Location: " . $url);
    }
// Performs a redirect once headers have been sent
    echo "<meta http-equiv=\"Refresh\" content=\"" . $delay . "; URL=" . $url . "\">";
    exit();
}

//
function prevent_page_cache() {
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Cache-Control: post-check=0, pre-check=0', false);
    header('Pragma: no-cache');
}



//Get IP address
function getRealIpAddr() {
    if (!emptyempty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
//to check ip is pass from proxy  
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

//Seconds to String
function secsToStr($secs) {
    if ($secs >= 86400) {
        $days = floor($secs / 86400);
        $secs = $secs % 86400;
        $r = $days . ' day';
        if ($days <> 1) {
            $r.='s';
        }if ($secs > 0) {
            $r.=', ';
        }
    }
    if ($secs >= 3600) {
        $hours = floor($secs / 3600);
        $secs = $secs % 3600;
        $r.=$hours . ' hour';
        if ($hours <> 1) {
            $r.='s';
        }if ($secs > 0) {
            $r.=', ';
        }
    }
    if ($secs >= 60) {
        $minutes = floor($secs / 60);
        $secs = $secs % 60;
        $r.=$minutes . ' minute';
        if ($minutes <> 1) {
            $r.='s';
        }if ($secs > 0) {
            $r.=', ';
        }
    }
    $r.=$secs . ' second';
    if ($secs <> 1) {
        $r.='s';
    }
    return $r;
}

//
function browser_detect() {
    $useragent = $_SERVER ['HTTP_USER_AGENT'];
    return useragent;
}





//Force file download
function force_download($file) {
    if ((isset($file)) && (file_exists($file))) {
        header("Content-length: " . filesize($file));
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $file . '"');
        readfile("$file");
    } else {
        echo "No file selected";
    }
}

//Create a tag cloud
function getCloud($data = array(), $minFontSize = 12, $maxFontSize = 30) {
    $minimumCount = min($data);
    $maximumCount = max($data);
    $spread = $maximumCount - $minimumCount;
    $cloudHTML = '';
    $cloudTags = array();

    $spread == 0 && $spread = 1;

    foreach ($data as $tag => $count) {
        $size = $minFontSize + ( $count - $minimumCount )
                * ( $maxFontSize - $minFontSize ) / $spread;
        $cloudTags[] = '<a style="font-size: ' . floor($size) . 'px'
                . '" class="tag_cloud" href="#" title="\'' . $tag .
                '\' returned a count of ' . $count . '">'
                . htmlspecialchars(stripslashes($tag)) . '</a>';
    }

    return join("\n", $cloudTags) . "\n";
}









function display_code($url) {
    $lines = file($url);
    foreach ($lines as $line_num => $line) {
// loop thru each line and prepend line numbers
        echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";
    }
}



function distance($lat1, $lon1, $lat2, $lon2, $unit) {

    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit = strtoupper($unit);

    if ($unit == "K") {
        return ($miles * 1.609344);
    } else if ($unit == "N") {
        return ($miles * 0.8684);
    } else {
        return $miles;
    }
}

function Sec2Time($time) {
    if (is_numeric($time)) {
        $value = array(
            "years" => 0, "days" => 0, "hours" => 0,
            "minutes" => 0, "seconds" => 0,
        );
        if ($time >= 31556926) {
            $value["years"] = floor($time / 31556926);
            $time = ($time % 31556926);
        }
        if ($time >= 86400) {
            $value["days"] = floor($time / 86400);
            $time = ($time % 86400);
        }
        if ($time >= 3600) {
            $value["hours"] = floor($time / 3600);
            $time = ($time % 3600);
        }
        if ($time >= 60) {
            $value["minutes"] = floor($time / 60);
            $time = ($time % 60);
        }
        $value["seconds"] = floor($time);
        return (array) $value;
    } else {
        return (bool) FALSE;
    }
}



function GetBetween($content, $start, $end) {
    $r = explode($start, $content);
    if (isset($r[1])) {
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}

function split_to_chunks($to, $text) {
    $total_length = (140 - strlen($to));
    $text_arr = explode(" ", $text);
    $i = 0;
    $message[0] = "";
    foreach ($text_arr as $word) {
        if (strlen($message[$i] . $word . ' ') <= $total_length) {
            if ($text_arr[count($text_arr) - 1] == $word) {
                $message[$i] .= $word;
            } else {
                $message[$i] .= $word . ' ';
            }
        } else {
            $i++;
            if ($text_arr[count($text_arr) - 1] == $word) {
                $message[$i] = $word;
            } else {
                $message[$i] = $word . ' ';
            }
        }
    }
    return $message;
}



function highlight($sString, $aWords) {
    if (!is_array($aWords) || empty($aWords) || !is_string($sString)) {
        return false;
    }

    $sWords = implode('|', $aWords);
    return preg_replace('@\b(' . $sWords . ')\b@si', '<strong style="background-color:yellow">$1</strong>', $sString);
}



function make_ranked($rank) {
    $last = substr($rank, -1);
    $seclast = substr($rank, -2, -1);
    if ($last > 3 || $last == 0)
        $ext = 'th';
    else if ($last == 3)
        $ext = 'rd';
    else if ($last == 2)
        $ext = 'nd';
    else
        $ext = 'st';

    if ($last == 1 && $seclast == 1)
        $ext = 'th';
    if ($last == 2 && $seclast == 1)
        $ext = 'th';
    if ($last == 3 && $seclast == 1)
        $ext = 'th';

    return $rank . $ext;
}

//function create_slug(strtolower($string)){
//$slug = preg_replace('/[^a-z0-9-]+/', '-', $string);
//return $slug;
//}



//////////////////////////////////
//define('APP_ID', 'abc_corp_ecommerce');
//Function to get a session variable
//
function session_get($key) {
    $k = APP_ID . '.' . $key;

    if (isset($_SESSION[$k])) {
        return $_SESSION[$k];
    }

    return false;
}

//Function set the session variable
//
function session_set($key, $value) {
    $k = APP_ID . '.' . $key;
    $_SESSION[$k] = $value;

    return true;
}

//



function encode_email($email = 'info@domain.com', $linkText = 'Contact Us', $attrs = 'class="emailencoder"') {
// remplazar aroba y puntos  
    $email = str_replace('@', '&#64;', $email);
    $email = str_replace('.', '&#46;', $email);
    $email = str_split($email, 5);

    $linkText = str_replace('@', '&#64;', $linkText);
    $linkText = str_replace('.', '&#46;', $linkText);
    $linkText = str_split($linkText, 5);

    $part1 = '<a href="ma';
    $part2 = 'ilto&#58;';
    $part3 = '" ' . $attrs . ' >';
    $part4 = '</a>';

    $encoded = '<script type="text/javascript">';
    $encoded .= "document.write('$part1');";
    $encoded .= "document.write('$part2');";
    foreach ($email as $e) {
        $encoded .= "document.write('$e');";
    }
    $encoded .= "document.write('$part3');";
    foreach ($linkText as $l) {
        $encoded .= "document.write('$l');";
    }
    $encoded .= "document.write('$part4');";
    $encoded .= '</script>';

    return $encoded;
}









function safe_redirect($url, $exit = true) {

    // Only use the header redirection if headers are not already sent
    if (!headers_sent()) {

        header('HTTP/1.1 301 Moved Permanently');
        header('Location: ' . $url);

        // Optional workaround for an IE bug (thanks Olav)
        header("Connection: close");
    }

    // HTML/JS Fallback:
    // If the header redirection did not work, try to use various methods other methods

    print '<html>';
    print '<head><title>Redirecting you...</title>';
    print '<meta http-equiv="Refresh" content="0;url=' . $url . '" />';
    print '</head>';
    print '<body onload="location.replace(\'' . $url . '\')">';

    // If the javascript and meta redirect did not work, 
    // the user can still click this link
    print 'You should be redirected to this URL:<br />';
    print "<a href='$url'>$url</a><br /><br />";

    print 'If you are not, please click on the link above.<br />';

    print '</body>';
    print '</html>';

    // Stop the script here (optional)
    if ($exit)
        exit;
}

function add_ending_slash($path) {

    $slash_type = (strpos($path, '\\') === 0) ? 'win' : 'unix';

    $last_char = substr($path, strlen($path) - 1, 1);

    if ($last_char != '/' and $last_char != '\\') {
        // no slash:
        $path .= ($slash_type == 'win') ? '\\' : '/';
    }

    return $path;
}



function bin2php($input_file, $output_file) {

    $i = file_get_contents($input_file);

    $b = array();
    $x = 0;
    $y = 0;

    for ($c = 0; $c < strlen($i); $c++) {
        $no = bin2hex($i[$c]);
        $b[$x] = isset($b[$x]) ? $b[$x] . '\\x' . $no : '\\x' . $no;
        if ($y >= 10) {
            $x++;
            $y = 0;
        }
        $y++;
    }

    $output = "<" . "?php\n";
    $output .= "\$f=\"";
    $output .= implode("\";\r\n\$f.=\"", $b);
    $output .= "\";\nprint \$f;";
    $output .= "\n?>";

    $fp = fopen($output_file, 'w+');
    fwrite($fp, $output);
    fclose($fp);
}



function syntax_highlight($code) {

    // this matches --> "foobar" <--
    $code = preg_replace(
            '/"(.*?)"/U', '&quot;<span style="color: #007F00">$1</span>&quot;', $code
    );

    // hightlight functions and other structures like --> function foobar() <--- 
    $code = preg_replace(
            '/(\s)\b(.*?)((\b|\s)\()/U', '$1<span style="color: #0000ff">$2</span>$3', $code
    );

    // Match comments (like /* */): 
    $code = preg_replace(
            '/(\/\/)(.+)\s/', '<span style="color: #660066; background-color: #FFFCB1;"><i>$0</i></span>', $code
    );

    $code = preg_replace(
            '/(\/\*.*?\*\/)/s', '<span style="color: #660066; background-color: #FFFCB1;"><i>$0</i></span>', $code
    );

    // hightlight braces:
    $code = preg_replace('/(\(|\[|\{|\}|\]|\)|\->)/', '<strong>$1</strong>', $code);

    // hightlight variables $foobar
    $code = preg_replace(
            '/(\$[a-zA-Z0-9_]+)/', '<span style="color: #0000B3">$1</span>', $code
    );

    /* The \b in the pattern indicates a word boundary, so only the distinct
     * * word "web" is matched, and not a word partial like "webbing" or "cobweb" 
     */

    // special words and functions
    $code = preg_replace(
            '/\b(print|echo|new|function)\b/', '<span style="color: #7F007F">$1</span>', $code
    );

    return $code;
}



function array_remove_empty($arr) {
    $narr = array();
    while (list($key, $val) = each($arr)) {
        if (is_array($val)) {
            $val = array_remove_empty($val);
            // does the result array contain anything?
            if (count($val) != 0) {
                // yes :-)
                $narr[$key] = $val;
            }
        } else {
            if (trim($val) != "") {
                $narr[$key] = $val;
            }
        }
    }
    unset($arr);
    return $narr;
}

function restore_array($arr) {
    if (!is_array($arr)) {
        return $arr;
    }
    $c = 0;
    $new = array();
    while (list($key, $value) = each($arr)) {
        if (is_array($value)) {
            $new[$c] = restore_array($value);
        } else {
            $new[$c] = $value;
        }
        $c++;
    }
    return $new;
}

function SimpleHash($str) {

    $n = 0;

    // The magic happens here:
    // I just loop trough all letters and add the
    // ASCII value to a integer variable. 
    for ($c = 0; $c < strlen($str); $c++)
        $n += ord($str[$c]);

    // After we went trough all letters
    // we have a number that represents the
    // content of the string

    return $n;
}



function md5_encrypt($plain_text, $password, $iv_len = 16) {
    $plain_text .= "\x13";
    $n = strlen($plain_text);
    if ($n % 16)
        $plain_text .= str_repeat("\0", 16 - ($n % 16));
    $i = 0;
    $enc_text = get_rnd_iv($iv_len);
    $iv = substr($password ^ $enc_text, 0, 512);
    while ($i < $n) {
        $block = substr($plain_text, $i, 16) ^ pack('H*', md5($iv));
        $enc_text .= $block;
        $iv = substr($block . $iv, 0, 512) ^ $password;
        $i += 16;
    }
    return base64_encode($enc_text);
}

function md5_decrypt($enc_text, $password, $iv_len = 16) {
    $enc_text = base64_decode($enc_text);
    $n = strlen($enc_text);
    $i = $iv_len;
    $plain_text = '';
    $iv = substr($password ^ substr($enc_text, 0, $iv_len), 0, 512);
    while ($i < $n) {
        $block = substr($enc_text, $i, 16);
        $plain_text .= $block ^ pack('H*', md5($iv));
        $iv = substr($block . $iv, 0, 512) ^ $password;
        $i += 16;
    }
    return preg_replace('/\\x13\\x00*$/', '', $plain_text);
}

function get_rnd_iv($iv_len) {
    $iv = '';
    while ($iv_len-- > 0) {
        $iv .= chr(mt_rand() & 0xff);
    }
    return $iv;
}



//
function remove_duplicated_values($arr) {
    $_a = array();
    while (list($key, $val) = each($arr)) {
        $_a[$val] = 1;
    }
    return array_keys($_a);
}







function random_array_element(&$a) {

    mt_srand((double) microtime() * 1000000);

    // get all array keys:
    $k = array_keys($a);

    // find a random array key:
    $r = mt_rand(0, count($k) - 1);
    $rk = $k[$r];

    // return the random key (if exists):
    return isset($a[$rk]) ? $a[$rk] : '';
}

//Shuffling the array keeping the keys and values together
function shuffle_assoc($array)
{
	$keys = array_keys($array);
	shuffle($keys);
	
	$result = array();
	foreach($keys as $k)
	{
		$result[$k] = $array[$k];
	}
	
	return $result;
}

function debug_val($val, $key = '', $depth = 0) {

    if (is_array($val)) {
        // call this function again with the "sub-array":
        array_walk($val, 'debug_val', $depth + 5);
    } else {
        // if we hit a string or bool, etc. then print it:
        print str_repeat('&nbsp;', $depth);
        print '<span style="color: blue;">' . $key . '</span>: ';
        print var_export($val, true);
        print "<br/>\n";
    }
}



function StringSizeToBytes($Size) {

    $Unit = strtolower($Size);
    $Unit = preg_replace('/[^a-z]/', '', $Unit);

    $Value = intval(preg_replace('/[^0-9]/', '', $Size));

    $Units = array('b' => 0, 'kb' => 1, 'mb' => 2, 'gb' => 3, 'tb' => 4);
    $Exponent = isset($Units[$Unit]) ? $Units[$Unit] : 0;

    return ($Value * pow(1024, $Exponent));
}



function curl_download($Url) {

    // is cURL installed yet?
    if (!function_exists('curl_init')) {
        die('Sorry cURL is not installed!');
    }

    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();

    // Now set some options (most are optional)
    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);

    // Set a referer
    curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");

    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    // Download the given URL, and return output
    $output = curl_exec($ch);

    // Close the cURL resource, and free system resources
    curl_close($ch);

    return $output;
}





function number_suffix($number) {

    // Validate and translate our input
    if (is_numeric($number)) {

        // Get the last two digits (only once)
        $n = $number % 100;
    } else {
        // If the last two characters are numbers
        if (preg_match('/[0-9]?[0-9]$/', $number, $matches)) {

            // Return the last one or two digits
            $n = array_pop($matches);
        } else {

            // Return the string, we can add a suffix to it
            return $number;
        }
    }

    // Skip the switch for as many numbers as possible.
    if ($n > 3 && $n < 21)
        return $number . 'th';

    // Determine the suffix for numbers ending in 1, 2 or 3, otherwise add a 'th'
    switch ($n % 10) {
        case '1': return $number . 'st';
        case '2': return $number . 'nd';
        case '3': return $number . 'rd';
        default: return $number . 'th';
    }
}



function autoUpdatingCopyright($startYear) {

    // given start year (e.g. 2004)
    $startYear = intval($startYear);

    // current year (e.g. 2007)
    $year = intval(date('Y'));

    // is the current year greater than the
    // given start year?
    if ($year > $startYear)
        return $startYear . '-' . $year;
    else
        return $startYear;
}

function dval($val, $print = true, $method = 'var_export') {

    // dval = Debug a VALue -> easy to remember for me

    if ($method == 'var_export') {
        $r = var_export($val, true);
    } else {
        $r = print_r($val, true);
    }

    if ($print) {
        print "<pre>[[" . htmlspecialchars($r) . "]]</pre>";
    } else {
        return "<pre>[[" . htmlspecialchars($r) . "]]</pre>";
    }
}

function RandomSplit($min, $max, $str) {
    $a = array();

    while ($str != '') {
        $p = rand($min, $max);
        $p = ($p > strlen($str)) ? strlen($str) : $p;

        $buffer = substr($str, 0, $p);
        $str = substr($str, $p, strlen($str) - $p);

        $a[] = $buffer;
    }
    return $a;
}

function post_request($url, $data, $referer = '') {

    // Convert the data array into URL Parameters like a=b&foo=bar etc.
    $data = http_build_query($data);

    // parse the given URL
    $url = parse_url($url);

    if ($url['scheme'] != 'http') {
        die('Error: Only HTTP request are supported !');
    }

    // extract host and path:
    $host = $url['host'];
    $path = $url['path'];

    // open a socket connection on port 80 - timeout: 30 sec
    $fp = fsockopen($host, 80, $errno, $errstr, 30);

    if ($fp) {

        // send the request headers:
        fputs($fp, "POST $path HTTP/1.1\r\n");
        fputs($fp, "Host: $host\r\n");

        if ($referer != '')
            fputs($fp, "Referer: $referer\r\n");

        fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
        fputs($fp, "Content-length: " . strlen($data) . "\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $data);

        $result = '';
        while (!feof($fp)) {
            // receive the results of the request
            $result .= fgets($fp, 128);
        }
    } else {
        return array(
            'status' => 'err',
            'error' => "$errstr ($errno)"
        );
    }

    // close the socket connection:
    fclose($fp);

    // split the result header from the content
    $result = explode("\r\n\r\n", $result, 2);

    $header = isset($result[0]) ? $result[0] : '';
    $content = isset($result[1]) ? $result[1] : '';

    // return as structured array:
    return array(
        'status' => 'ok',
        'header' => $header,
        'content' => $content
    );
}



function elapsed_time($timestamp, $precision = 2) {
    $time = time() - $timestamp;
    $a = array('decade' => 315576000, 'year' => 31557600, 'month' => 2629800, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'min' => 60, 'sec' => 1);
    $i = 0;
    foreach ($a as $k => $v) {
        $$k = floor($time / $v);
        if ($$k)
            $i++;
        $time = $i >= $precision ? 0 : $time - $$k * $v;
        $s = $$k > 1 ? 's' : '';
        $$k = $$k ? $$k . ' ' . $k . $s . ' ' : '';
        @$result .= $$k;
    }
    return $result ? $result . 'ago' : '1 sec to go';
}




  
 



?>
